from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QIcon, QPainter, QPixmap, QImageReader

from utils.index import resource_path


# 加载并优化高清图片
def load_hd_pixmap(win, image_path) -> QPixmap:
    # # 获取屏幕的物理DPI
    screen = win.screen()
    # dpi = screen.physicalDotsPerInch()
    #
    # # 根据DPI动态加载不同分辨率图片
    # if dpi >= 144:
    #     pixmap = QPixmap("image@2x.png")  # 高分辨率版本
    # else:
    #     pixmap = QPixmap("image.png")  # 标准分辨率版本
    #
    # # 如果只有单张图片，进行智能缩放
    # if pixmap.isNull():
    #     pixmap = QPixmap(image_path)

    img = load_large_image(image_path)
    if img:
        pixmap = QPixmap(img)
    else:
        pixmap = QPixmap(image_path)

    # 计算目标尺寸（保留原始像素细节）
    target_size = QSize(
        int(pixmap.width() * screen.devicePixelRatio()),
        int(pixmap.height() * screen.devicePixelRatio())
    )

    return pixmap.scaled(
        target_size,
        Qt.AspectRatioMode.KeepAspectRatio,
        Qt.TransformationMode.SmoothTransformation
    )


# 安全加载大图像，自动缩放至指定尺寸以下
def load_large_image(file_path, max_size=5000):
    """安全加载大图像，自动缩放至指定尺寸以下"""
    # 先获取图像原始尺寸，不加载全部内容
    reader = QImageReader(file_path)
    size = reader.size()
    out_path = resource_path("./static/img/img_min.png")

    if size.isValid():
        width, height = size.width(), size.height()
        # 计算缩放比例
        if width > max_size or height > max_size:
            ratio = min(max_size / width, max_size / height)
            reader.setScaledSize(
                size.scaled(int(width * ratio), int(height * ratio), Qt.AspectRatioMode.KeepAspectRatio))

        # 加载缩放后的图像
        image = reader.read()
        image.save(out_path, "PNG")
        return out_path
    return None